package com.situ.b2c.util;

import java.io.IOException;
import java.io.InputStream;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

public class MyBatisUtil {

	private static SqlSessionFactory sqlSessionFactory;
	
	
	/**
	 *  得到sqlSessionFactory实例，一个项目中只需要一个实例
	 * @return
	 */
	static {
		if (sqlSessionFactory == null) {
			InputStream inputStream = null;
			try {
				inputStream = Resources.getResourceAsStream("mybatis/mybatis-config.xml");
			} catch (IOException e) {
				e.printStackTrace();
			}
			 sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
		}
		
	}
	
	
	
	/**
	 *  #得到Dao实例
	 * @param <T>
	 * @param type
	 * @return 
	 */
	public static <T> T buildDaoInstance(Class<T> type){
		//设置sqlSession自动提交
		boolean autoCommit = true;
		SqlSession sqlSession = sqlSessionFactory.openSession(autoCommit);
		return sqlSession.getMapper(type);
		
	}
	
	
	
	/*
	 * public static SqlSessionFactory buildSqlSessionFactory() {
	 * 
	 * 
	 * return sqlSessionFactory; }
	 */
}
